package org.programmers.anonymous.fightrobots.model;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MessageSerializer {

	private static final Logger logger = LoggerFactory.getLogger(MessageSerializer.class);
	
	private final ObjectMapper mapper = new ObjectMapper();

    public String serialize( final Message message ) 
    {
        final StringWriter writer = new StringWriter();
        
        try 
        {
            mapper.writeValue( writer, message );
            //logger.error("message to serialize" +message);
            return writer.toString();
        } 
        catch( final IOException ex ) 
        {
            throw new RuntimeException( ex.getMessage(), ex );
        } 
        finally 
        {
            try { writer.close(); } catch ( final IOException ex ) { /* Nothing to do here */ }
        }
    }

    public Message deserialize( final String str ) 
    {
        final StringReader reader = new StringReader( str );
        
        try 
        {
            return mapper.readValue( reader, Message.class );
        } 
        catch( final IOException ex ) 
        {
        	logger.error(ex.getLocalizedMessage());
            throw new RuntimeException( ex.getMessage(), ex );
        } 
        catch(Exception e)
        {
        	logger.error(e.getLocalizedMessage());
        	 throw new RuntimeException( e.getMessage(), e );
        }
        finally {
            reader.close();
        }
    }
}
